package com.example.demorabbitmqlisten.rabbitmq;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * MQ消息校验工具类
 *
 * @author rockzhan 2021-04-13 12:19
 * @version 1.0
 */
@Slf4j
public class MqVerifyUtil {

    /**
     * 校验MQ消息payload<br/>
     * 先将payload进行国密4解密，再进行字典排序，最后在进行RSA加密
     *
     * @param payload MQ消息payload部分字符串
     * @param sign    MQ消息sign
     * @return payload国密4解密、字典排序、RSA加密后与sign对比结果
     * @author rockzhan 2021-04-13 12:23
     */
    public static boolean verify(String payload, String sign){
        log.info("待国密4解密payload=[{}]", payload);
        String decryptPayload = Sm4Util.decrypt(payload);
        log.info("国密4解密后payload=[{}]", decryptPayload);

        log.info("payload排序, 排序前=[{}]", decryptPayload);
        String sortJson = JacksonUtil.sortJson(decryptPayload);
        log.info("payload排序, 排序后=[{}]", sortJson);

        log.info("MQ消息RSA解密验证开始");
        String encryptJson = RsaUtil.encrypt(sortJson);
        boolean verify = StrUtil.equals(encryptJson, sign);
        log.info("MQ消息RSA解密验证结束, 结果=[{}]", verify);
        return verify;
    }

}
